package com.cx.common.swagger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author:chenxiaoyi
 * @Date:2020/4/29 15:38
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Autowired
    private Environment environment;

    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cx"))
                .paths(PathSelectors.any())
                .build()
                //接口信息
                .apiInfo(apiInfo())
                //全局参数
                .globalOperationParameters(getGlobalOperationParameters())
                //全站统一参数token
                .securitySchemes(authToken())
                ;
    }

    //接口信息配置
    private ApiInfo apiInfo(){
        String serverName = environment.getProperty("server.name");
        return  new ApiInfoBuilder()
                .title(serverName+"服务SwaggerUI")
                .description(serverName+"服务接口文档")
                .version("1.1.1")
                .license("The Cxy License")
                .licenseUrl("http://www.baidu.com")
                .build();
    }

    //全局参数配置
    private List<Parameter> getGlobalOperationParameters() {
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        // header query cookie
        parameterBuilder.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false);
        pars.add(parameterBuilder.build());
        parameterBuilder.name("userId").description("用户id").modelRef(new ModelRef("string")).parameterType("header").required(false);
        pars.add(parameterBuilder.build());
        return pars;
    }
    //全站统一参数配置，一般是token。
    private  List<ApiKey> authToken() {
        return Collections.singletonList(new ApiKey("token", "token", "header"));
    }

}
